import path from 'path';
import { fileURLToPath } from 'url';
import readPackageInfo from './readPackageInfo.js';
import { Command } from 'commander';
import getPromptQuestions from './promptQuestions.js';
import {
  createProjectDirectory,
  getTemplateDir,
  getTargetDir,
  handleLanguageChoice,
  replaceProjectName,
  printSuccessMessage
} from './projectCreation.js';
import { initializeGitRepository } from './gitUtils.js';
import { renderTemplateFiles } from './templateRendering.js';

const program = new Command();
const __dirname = path.dirname(fileURLToPath(import.meta.url));

// 定义命令行选项并添加描述信息
program
  .name('create-a3ui') // 设置程序名称
  .description('用于创建前端项目的工具') // 设置程序描述
  .option('-n, --project-name <name>', '项目英文名称')
  .option('-c, --project-chinese-name <name>', '项目中文名称')
  .option('-t, --target-dir <dir>', '生成工程的目标文件夹地址')
  .option('-pt, --project-type <type>', '工程类型，可选值：微前端工程, 单一前端工程, 微前端子工程')
  .option('-tm, --template <template>', '项目脚本类型，可选值：Vite + TypeScript, Vite + JavaScript')
  .option('-l, --lowcode', '是否启用低代码')
  .parse(process.argv);

const options = program.opts();

async function run() {
  try {
    const info = await readPackageInfo();
    console.log(`Name: ${info.name}`);
    console.log(`Version: ${info.version}`);
    if (info.description) {
      console.log(`Description: ${info.description}`);
    }
    console.log(`是否为前端工程: ${info.isFrontend ? '是' : '否'}`);
  } catch (error) {
    console.error('读取 package.json 信息时出错:', error);
  }

  const answers = await getPromptQuestions(options);

  try {
    const projectDir = createProjectDirectory(answers.projectName, answers.targetDir);
    const templateDir = getTemplateDir(answers.projectType);
    const targetDir = getTargetDir(answers.projectType, projectDir, answers.projectName);
    await renderTemplateFiles(templateDir, targetDir, answers);
    handleLanguageChoice(answers, targetDir);
    replaceProjectName(answers, projectDir, targetDir);
    initializeGitRepository(projectDir);
    printSuccessMessage(answers.projectName);
  } catch (error) {
    console.error(`项目创建失败: ${error.message}`);
  }
}

run();